package net.onceface.web.resources;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.onceface.application.OrderApplication;
import net.onceface.core.domain.Order;
import net.onceface.core.domain.enums.OrderStatus;
import net.onceface.core.domain.enums.Payment;
import net.onceface.infra.spring.ioc.InstanceFactory;

import org.apache.log4j.Logger;

import com.unionpay.acp.sdk.AcpService;
import com.unionpay.acp.sdk.LogUtil;
import com.unionpay.acp.sdk.SDKConstants;

/**
 * 银联跳转网关支付后台通知
 * @throws UnsupportedEncodingException 
 * */
public class BackRcvResponse extends HttpServlet{

	Logger logger  = Logger.getLogger(BackRcvResponse.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = -6458471857332038337L;
	
	private OrderApplication application;
	@Override
	public void init() throws ServletException {
		application = InstanceFactory.getInstance(OrderApplication.class);
		super.init();
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.info("BackRcvResponse接收后台通知开始!");
		req.setCharacterEncoding("ISO-8859-1");
		String encoding = req.getParameter(SDKConstants.param_encoding);
		// 获取银联通知服务器发送的后台通知参数
		Map<String, String> reqParam = getAllRequestParam(req);
		LogUtil.printRequestLog(reqParam);
		if(reqParam == null){
			logger.warn("后台通知参数是空的！");
		}
		Map<String, String> valideData = null;
		if (null != reqParam && !reqParam.isEmpty()) {
			Iterator<Entry<String, String>> it = reqParam.entrySet().iterator();
			valideData = new HashMap<String, String>(reqParam.size());
			while (it.hasNext()) {
				Entry<String, String> e = it.next();
				String key = (String) e.getKey();
				String value = (String) e.getValue();
				value = new String(value.getBytes("ISO-8859-1"), encoding);
				valideData.put(key, value);
			}
		}
		//重要！验证签名前不要修改reqParam中的键值对的内容，否则会验签不过
		if (!AcpService.validate(valideData, encoding)) {
			logger.info("验证签名结果[失败]!");
			//验签失败，需解决验签问题
		} else {
			//【注：为了安全验签成功才应该写商户的成功处理逻辑】交易成功，更新商户订单状态
			//获取后台通知的数据，其他字段也可用类似方式获取		
			String orderId =valideData.get("orderId");
			logger.info("验证签名结果[成功]! 订单编号--->" + orderId);
			Order order = Order.getOrderByOrderNumber(orderId);
			if(order != null){
				if(order.getOrderStatus() != OrderStatus.A){
					switch(order.getOrderStatus()){
						case B: logger.info("此订单编号已付款--->" + orderId); break;
						case C: logger.info("此订单编号已发货--->" + orderId); break;
						case D: logger.info("此订单编号已完成--->" + orderId); break;
						case E: logger.info("此订单编号已取消--->" + orderId); break;
						default: break;
					}
				}else{
					order.setOrderStatus(OrderStatus.B);
					order.setPayment(Payment.Bank);
					application.update(order);
					logger.info("付款成功，状态改为代发货，订单编号--->" + orderId);
				}	
			}else{
				logger.info("没找到此订单编号--->" + orderId);	
			}
			//获取应答码，收到后台通知了respCode的值一般是00，可以不需要根据这个应答码判断。
			String respCode =valideData.get("respCode");
		}
		logger.info("BackRcvResponse接收后台通知结束");
		//返回给银联服务器http 200  状态码
		resp.getWriter().print("ok");
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
			IOException {
		this.doPost(req, resp);
	}

	/**
	 * 获取请求参数中所有的信息
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, String> getAllRequestParam(final HttpServletRequest request) {
		Map<String, String> res = new HashMap<String, String>();
		Enumeration<?> temp = request.getParameterNames();
		if (null != temp) {
			while (temp.hasMoreElements()) {
				String en = (String) temp.nextElement();
				String value = request.getParameter(en);
				res.put(en, value);
				//在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
				System.out.println("ServletUtil类247行  temp数据的键=="+en+"     值==="+value);
				if (null == res.get(en) || "".equals(res.get(en))) {
					res.remove(en);
				}
			}
		}
		return res;
	}
}
